package cn.trigram.json.serializer;

import cn.trigram.lang.ConvertUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.type.WritableTypeId;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JacksonStdImpl;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
import java.lang.reflect.Type;

/**
 * 1. 修正jackson在long序列化的bug。如果数值在integer范围内，那实际上会转换为integer，这样在进行long的强制转换时会报错
 * 2. 修正前端的number精度不能超过17位
 *
 * @version 1.0.0
 * @date 2022/08/02 16:09:59
 * @since 1.0.0
 */
@JacksonStdImpl
public class LongSerializer extends StdSerializer<Long> {
    public LongSerializer() {
        super(Long.class, false);
    }

    @Override
    public void serialize(Long value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeString(ConvertUtil.toStr(value));
    }

    @Override
    public void serializeWithType(Long value, JsonGenerator gen, SerializerProvider provider, TypeSerializer typeSer) throws IOException {
        final WritableTypeId typeId = typeSer.writeTypePrefix(gen, typeSer.typeId(value, JsonToken.VALUE_STRING));
        serialize(value, gen, provider);
        typeSer.writeTypeSuffix(gen, typeId);
    }

    @Override
    public JsonNode getSchema(SerializerProvider provider, Type typeHint) {
        return createSchemaNode("string", true);
    }

    @Override
    public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException {
        visitStringFormat(visitor, typeHint);
    }
}
